<template>
  <div class="singer">
    <list-view :data="singers"></list-view>
  </div>
</template>

<script type="text/ecmascript-6">
  import {
    getSingerList
  } from 'api/singer'
  import {
    ERR_OK
  } from 'api/config'
  import Singer from 'common/js/singer'
  import ListView from 'base/listview/listview'

  const HOT_NAME = '热门'
  const LEN = 10
  export default {
    data() {
      return {
        singers: []
      }
    },
    created() {
      this._getSingerList()
    },
    methods: {
      _getSingerList() {
        getSingerList().then((res) => {
          if (res.code === ERR_OK) {
            this.singers = this._normalizeSinger(res.data.list)
            console.log(this.singers)
          }
        })
      },
      _normalizeSinger(list) {
        let map = {
          hot: {
            title: HOT_NAME,
            items: []
          }
        }
        list.forEach(function(items, index, list) {
          // 前十位作为hot列表
          if (index < LEN) {
            map.hot.items.push(new Singer({
              id: items.Fsinger_mid,
              name: items.Fsinger_name
            }))
          }
          // >>> map = {hot:{title:xxx,items:[]}, B:{title:xxx,items:[]}, A:{title:xxx,items:[]} ……}
          const key = items.Findex
          if (!map[key]) {
            map[key] = {
              title: key,
              items: []
            }
          }
          map[key].items.push(new Singer({
            id: items.Fsinger_mid,
            name: items.Fsinger_name
          }))
        })
        // 创建数组Array以便可以有A-Z的顺序
        let hot = []
        let ret = []
        for (let i in map) {
          let value = map[i]
          if (value.title.match(/[A-Za-z]/)) {
            ret.push(value)
          } else if (value.title === HOT_NAME) {
            hot.push(value)
          }
        }
        ret.sort((a, b) => {
          return a.title.charCodeAt(0) - b.title.charCodeAt(0)
        })
        return hot.concat(ret)
      }
    },
    components: {
      ListView
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .singer
    position: fixed
    top: 88px
    bottom: 0
    width: 100%
</style>
